package com.github.axet.audiorecorder.simple.app

import android.content.Context
import android.content.SharedPreferences
import android.media.MediaRecorder
import android.os.Build
import android.preference.PreferenceManager

class RecordingConfig {
    
    var sampleRate: Int
    var audioFormat: String
    var audioSource: Int
    var storagePath: String?
    var retentionDays: Int
    
    constructor() {
        this.sampleRate = DEFAULT_SAMPLE_RATE
        this.audioFormat = DEFAULT_AUDIO_FORMAT
        this.audioSource = getDefaultAudioSource()
        this.storagePath = null
        this.retentionDays = DEFAULT_RETENTION_DAYS
    }
    
    fun saveToPreferences(context: Context) {
        val prefs = PreferenceManager.getDefaultSharedPreferences(context)
        val editor = prefs.edit()
        
        editor.putInt(PREF_SAMPLE_RATE, sampleRate)
        editor.putString(PREF_AUDIO_FORMAT, audioFormat)
        editor.putInt(PREF_AUDIO_SOURCE, audioSource)
        editor.putInt(PREF_RETENTION_DAYS, retentionDays)
        storagePath?.let {
            editor.putString(PREF_STORAGE_PATH, it)
        }
        
        editor.apply()
    }
    
    fun getAudioSourceName(): String {
        return when (audioSource) {
            MediaRecorder.AudioSource.MIC -> "麦克风"
            MediaRecorder.AudioSource.VOICE_COMMUNICATION -> "内部音频"
            else -> "未知"
        }
    }
    
    fun getSampleRateText(): String {
        return "${sampleRate / 1000} kHz"
    }
    
    fun getAudioFormatText(): String {
        return audioFormat.uppercase()
    }
    
    companion object {
        // 配置键
        const val PREF_SAMPLE_RATE = "sample_rate"
        const val PREF_AUDIO_FORMAT = "audio_format"
        const val PREF_AUDIO_SOURCE = "audio_source"
        const val PREF_STORAGE_PATH = "storage_path"
        const val PREF_RETENTION_DAYS = "retention_days"
        
        // 可配置的默认值 - 可以通过修改这些常量来改变默认行为
        const val DEFAULT_SAMPLE_RATE = 16000  // 可选: 8000, 16000, 22050, 44100, 48000
        const val DEFAULT_AUDIO_FORMAT = "wav"  // 可选: "wav", "m4a"
        const val DEFAULT_AUDIO_SOURCE_MIC = MediaRecorder.AudioSource.MIC
        const val DEFAULT_AUDIO_SOURCE_INTERNAL = MediaRecorder.AudioSource.VOICE_COMMUNICATION
        const val DEFAULT_RETENTION_DAYS = 7  // 默认保留7天的录音
        
        // 是否优先使用内部音频录制（如果系统支持）
        const val PREFER_INTERNAL_AUDIO = true
        
        // 支持的采样率选项
        val SUPPORTED_SAMPLE_RATES = intArrayOf(8000, 16000, 22050, 44100, 48000)
        
        // 支持的音频格式选项
        val SUPPORTED_AUDIO_FORMATS = arrayOf("wav", "m4a")
        
        // 支持的保留天数选项
        val SUPPORTED_RETENTION_DAYS = intArrayOf(1, 3, 7, 14, 30, 90)
        
        fun fromPreferences(context: Context): RecordingConfig {
            val prefs = PreferenceManager.getDefaultSharedPreferences(context)
            val config = RecordingConfig()
            
            config.sampleRate = prefs.getInt(PREF_SAMPLE_RATE, DEFAULT_SAMPLE_RATE)
            config.audioFormat = prefs.getString(PREF_AUDIO_FORMAT, DEFAULT_AUDIO_FORMAT) ?: DEFAULT_AUDIO_FORMAT
            config.audioSource = prefs.getInt(PREF_AUDIO_SOURCE, getDefaultAudioSource())
            config.storagePath = prefs.getString(PREF_STORAGE_PATH, null)
            config.retentionDays = prefs.getInt(PREF_RETENTION_DAYS, DEFAULT_RETENTION_DAYS)
            
            return config
        }
        
        fun getDefaultAudioSource(): Int {
            // 根据配置决定是否优先使用内部音频录制
            return if (PREFER_INTERNAL_AUDIO && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                DEFAULT_AUDIO_SOURCE_INTERNAL
            } else {
                DEFAULT_AUDIO_SOURCE_MIC
            }
        }
        
        /**
         * 创建具有指定参数的配置实例
         */
        fun createConfig(sampleRate: Int, audioFormat: String, audioSource: Int): RecordingConfig {
            val config = RecordingConfig()
            config.sampleRate = if (isValidSampleRate(sampleRate)) sampleRate else DEFAULT_SAMPLE_RATE
            config.audioFormat = if (isValidAudioFormat(audioFormat)) audioFormat else DEFAULT_AUDIO_FORMAT
            config.audioSource = audioSource
            return config
        }
        
        /**
         * 验证采样率是否支持
         */
        fun isValidSampleRate(sampleRate: Int): Boolean {
            return SUPPORTED_SAMPLE_RATES.contains(sampleRate)
        }
        
        /**
         * 验证音频格式是否支持
         */
        fun isValidAudioFormat(format: String?): Boolean {
            if (format == null) return false
            return SUPPORTED_AUDIO_FORMATS.any { it.equals(format, ignoreCase = true) }
        }
        
        /**
         * 获取系统是否支持内部音频录制
         */
        fun isInternalAudioSupported(): Boolean {
            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
        }
        
        /**
         * 验证保留天数是否支持
         */
        fun isValidRetentionDays(days: Int): Boolean {
            return SUPPORTED_RETENTION_DAYS.contains(days)
        }
        
        /**
         * 创建具有指定保留天数的配置实例
         */
        fun createConfigWithRetention(sampleRate: Int, audioFormat: String, audioSource: Int, retentionDays: Int): RecordingConfig {
            val config = createConfig(sampleRate, audioFormat, audioSource)
            config.retentionDays = if (isValidRetentionDays(retentionDays)) retentionDays else DEFAULT_RETENTION_DAYS
            return config
        }
    }
}